<template>
  <div class="print-container" ref="printContainerRef">
    <!-- 打印内容 -->
    <div class="print-content" v-if="orderData">
      <!-- 头部信息 -->
      <div class="print-header">
        <div class="qrcode">
          <img :src="qrCodeUrl" alt="二维码" />
        </div>
        <div class="title">
          <h1>{{ orderData.title }}</h1>
          <h2>{{ orderData.subTitle }}</h2>
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="order-info">
        <div class="info-item">
          <span class="label">客户：</span>
          <span class="value">{{ orderData.customer }}</span>
        </div>
        <div class="info-item">
          <span class="label">销售人：</span>
          <span class="value">{{ orderData.seller }}</span>
        </div>
        <div class="info-item-date">
          <span class="label">单据日期：</span>
          <span class="value">{{ formatDate(orderData.date) }}</span>
        </div>
        <div class="info-item-single">
          <span class="label">单据编号：</span>
          <span class="value">{{ orderData.orderNo }}</span>
        </div>
      </div>
      <!-- 商品表格 -->
      <table class="goods-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>商品名称</th>
            <th>型号规格</th>
            <th>数量</th>
            <th>单位</th>
            <th>单价</th>
            <th>金额</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in orderData.items" :key="index">
            <td>{{ item.no }}</td>
            <td>
              <div class="product-name">
                <span v-if="item.brand_name">({{ item.brand_name }})</span>
                {{ item.name }}
              </div>
            </td>
            <td>{{ item.sku_name || '无' }}</td>
            <td>{{ item.quantity }}</td>
            <td>{{ item.unit }}</td>
            <td>{{ formatPrice(item.price) }}</td>
            <td>{{ formatPrice(item.amount) }}</td>
            <td>{{ item.remark }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr class="total-row">
            <td colspan="2">合计</td>
            <td :colspan="1"></td>
            <td>{{ orderData.total.quantity }}</td>
            <td></td>
            <td></td>
            <td>{{ formatPrice(orderData.total.amount) }}</td>
            <td></td>
          </tr>
          <tr>
            <td :colspan="8" class="amount-in-words">
              合计金额大写: {{ orderData.total.amountInWords }}
            </td>
          </tr>
        </tfoot>
      </table>

      <!-- 底部信息 -->
      <div class="footer-info">
        <div class="maker">制单人：{{ orderData.maker }}</div>
        <div class="customer-sign">{{ orderData.customer_sign }}</div>
      </div>
    </div>

    <!-- 打印按钮 -->
    <div class="print-buttons" v-if="!isPrinting">
      <el-button type="primary" @click="handlePrint">打印</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </div>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { getSingleSalesInfo } from '@/api/single'
  import { convertCurrency } from '@/utils/helper'
  import { useRoute } from 'vue-router'
  import { getOrderQrcode } from '@/api/print'
  import { printSingle } from '@/utils/print'
  // 从路由参数中获取 id 和 title
  const route = useRoute()
  const orderId = computed(() => route.query.id)
  const pageTitle = computed(() =>
    decodeURIComponent(route.query.title || '销售送货单')
  )

  const orderData = ref(null)
  const specNames = ref([])
  const isPrinting = ref(false)
  const printContainerRef = ref(null)
  const qrCodeUrl = ref('')

  // 生成默认的二维码URL
  const generateQRCode = async (id) => {
    console.log(process.env, 'process.env')
    const res = await getOrderQrcode({
      page: 'pagesShop/order/orderInfo',
      scene: `id=${id}`,
      env_version: process.env.VUE_APP_VERSION,
    })
    return res.data
  }

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return ''
    return dateString.substring(0, 10)
  }

  // 格式化价格
  const formatPrice = (price) => {
    return Number(price).toFixed(2)
  }

  // 获取订单数据
  const fetchOrderData = async (id) => {
    try {
      const { data } = await getSingleSalesInfo({ id })
      if (!data) {
        ElMessage.error('获取订单数据失败')
        return
      }
      const orderInfo = data
      if (orderInfo.order_detail.length > 30) return moreGoodPrint(id)
      // 解析规格名称
      const spec = orderInfo.order_detail[0].goods_spec_name.split('??')
      specNames.value = spec

      // 准备数据
      orderData.value = {
        title: orderInfo.base_info.supplier_name,
        subTitle: pageTitle.value,
        orderNo: orderInfo.base_info.order_sn,
        date: orderInfo.base_info.create_time,
        customer: orderInfo.base_info.shop_name,
        seller: orderInfo.base_info.sales_person_name,
        items: orderInfo.order_detail.map((goods, index) => {
          const specValue = goods.goods_value_name.split('??')
          const obj = {
            no: index + 1,
            name: goods.product_name || goods.goods_name,
            quantity: Number(goods.quantity || 0),
            price: Number(goods.price || 0),
            amount: Number(goods.price || 0) * Number(goods.quantity || 0),
            remark: goods.remark || '',
            brand_name: goods.brand_name || '',
            sku_name: goods.goods_value_name.replace('??', ',') || '',
            unit: goods.unit,
          }

          // 添加规格属性
          spec.forEach((item, index) => {
            obj[item] = specValue[index] || '无'
          })

          return obj
        }),
        total: {
          quantity: orderInfo.order_detail.reduce(
            (total, goods) => total + Number(goods.quantity || 0),
            0
          ),
          amount: Number(orderInfo.base_info.pay_amount),
        },
        maker: orderInfo.base_info.sales_person_name,
        customer_sign: '客户签字:___________',
      }

      // 计算金额大写
      orderData.value.total.amountInWords = convertCurrency(
        orderData.value.total.amount
      )
      // 生成二维码
      qrCodeUrl.value = await generateQRCode(id)
    } catch (error) {
      console.error('获取订单数据失败:', error)
      ElMessage.error('获取订单数据失败')
    }
  }

  // 处理打印
  const handlePrint = () => {
    isPrinting.value = true
    // 创建打印样式
    const style = document.createElement('style')
    style.type = 'text/css'
    style.innerHTML = `
    @media print {
      body * {
        visibility: hidden;
      }
      .print-content, .print-content * {
        visibility: visible;
        color: #000 !important;
      }
      .print-content {
        position: absolute;
        left: -70mm;
        right: 0;
        top: 0;
        width: 165mm;
        max-width: 165mm;
        margin: 0 auto;
        box-sizing: border-box;
      }
      .print-buttons {
        display: none !important;
      }
      @page {
        size: auto;
        marks: none;
        margin:0mm;
      }
      /* 强制所有文本元素为黑色 */
    .print-content h1,
    .print-content h2,
    .print-content span,
    .print-content div,
    .print-content td,
    .print-content th,
    .print-content p {
      color: #000 !important;
    }
      /* 调整表格列宽 */
      .goods-table th:nth-child(1),
  .goods-table td:nth-child(1) {
    width: 50px; /* 序号列宽度 */
  }

  .goods-table th:nth-child(2),
  .goods-table td:nth-child(2) {
    width: 25%; /* 商品名称列宽度 */
  }
  .goods-table th:nth-child(3),
  .goods-table td:nth-child(3) {
    width: 25%; /* 商品名称列宽度 */
  }
   .goods-table th:nth-child(4),
  .goods-table td:nth-child(4) {
    width: 45px; /* 数量宽度 */
  }
  .goods-table th:nth-child(n + 5):nth-child(-n + 5),
  .goods-table td:nth-child(n + 5):nth-child(-n + 5) {
    width: 45px; /* 单位宽度 */
  }
    }
  `
    document.head.appendChild(style)

    // 延迟执行打印，确保样式已应用
    setTimeout(() => {
      window.print()
      // 打印完成后移除样式
      document.head.removeChild(style)
      isPrinting.value = false
    }, 300)
  }

  // 关闭窗口
  const handleClose = () => {
    window.close()
  }

  // 暴露打印方法给父组件
  defineExpose({
    print: (id) => {
      fetchOrderData(id)
      setTimeout(handlePrint, 500)
    },
  })

  const moreGoodPrint = (id) => {
    printSingle([{ id: id }])
  }

  // 组件挂载时，获取路由参数中的订单ID并获取数据
  onMounted(async () => {
    if (orderId.value) {
      await fetchOrderData(orderId.value)
    }
  })
</script>

<style scoped>
  .print-container {
    max-width: 210mm; /* A4宽度 */
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    font-family: '黑体', '微软雅黑', '宋体', serif;
    color: #000 !important;
  }
  /* 强制所有文本元素为黑色 */
  .print-content h1,
  .print-content h2,
  .print-content span,
  .print-content div,
  .print-content td,
  .print-content th,
  .print-content p {
    color: #000 !important;
  }
  .print-header {
    display: flex;
    position: relative;
    height: 100px;
  }

  .qrcode {
    position: absolute;
    left: 0;
    top: 0;
    width: 80px;
    height: 80px;
  }

  .qrcode img {
    width: 100%;
    height: 100%;
  }

  .title {
    flex: 1;
    text-align: center;
  }

  .title h1 {
    font-size: 24px;
    font-weight: bold;
    margin: 0 0 10px 0;
  }

  .title h2 {
    font-size: 20px;
    font-weight: bold;
    margin: 0;
  }
  .order-info {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-between;
    font-size: 14px;
    margin-bottom: 20px;
  }

  .info-item,
  .info-item-date,
  .info-item-single {
    flex: 1;
    margin-bottom: 10px;
    white-space: nowrap;
    display: flex;
  }

  .label {
    font-weight: bold;
  }

  .goods-table {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
    margin-bottom: 20px;
    font-size: 12px;
    page-break-inside: auto;
  }

  /* 调整表格列宽 */
  .goods-table th:nth-child(1),
  .goods-table td:nth-child(1) {
    width: 50px; /* 序号列宽度 */
  }

  .goods-table th:nth-child(2),
  .goods-table td:nth-child(2) {
    width: 25%; /* 商品名称列宽度 */
  }
  .goods-table th:nth-child(3),
  .goods-table td:nth-child(3) {
    width: 25%; /* 商品名称列宽度 */
  }
  .goods-table th:nth-child(4),
  .goods-table td:nth-child(4) {
    width: 45px; /* 数量宽度 */
  }
  .goods-table th:nth-child(n + 5):nth-child(-n + 5),
  .goods-table td:nth-child(n + 5):nth-child(-n + 5) {
    width: 45px; /* 单位宽度 */
  }

  .goods-table th,
  .goods-table td {
    border: 1px solid #000;
    padding: 8px;
    text-align: start;
  }

  .goods-table th {
    background-color: #f2f2f2;
    font-weight: bold;
  }

  .product-name {
    text-align: left;
  }

  .total-row {
    font-weight: bold;
  }

  .amount-in-words {
    text-align: left;
    font-weight: bold;
  }

  .footer-info {
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
    font-size: 14px;
  }

  .print-buttons {
    text-align: center;
    margin-top: 20px;
  }

  /* 针对打印优化的样式 */
  @media print {
    .print-container {
      box-shadow: none;
      padding: 0;
      width: 170mm;
      max-width: 170mm;
      margin: 0 auto;
    }

    .print-buttons {
      display: none;
    }

    /* 确保黑色文字在打印时保持黑色 */
    * {
      color-adjust: exact !important;
      -webkit-print-color-adjust: exact !important;
      print-color-adjust: exact !important;
    }
    .info-item {
      width: 20%;
      margin-bottom: 10px;
    }
    .info-item-date {
      width: 31%;
      margin-bottom: 10px;
    }
    .info-item-single {
      flex: 1;
      margin-bottom: 10px;
    }

    /* 增强表格边框在打印时的可见度 */
    .goods-table th,
    .goods-table td {
      border: 1.5px solid #000;
    }

    .goods-table {
      width: 100%;
      table-layout: fixed;
    }

    /* 优化表格单元格内容 */
    .goods-table th,
    .goods-table td {
      padding: 6px;
      font-size: 12px;
    }
  }
</style>
